<template>
  <view class="appeal-complaint-stats-container">
    <z-paging 
      ref="paging" 
      v-model="dataList" 
      @query="queryList"
      :auto="false"
      :refresher-enabled="true"
      :loading-more-enabled="true"
      :empty-view-text="'暂无数据'"
      class="list-paging"
    >
      <template #top>
        <!-- 页面标题 -->
        <view class="page-header">
          <view class="header-title">投申诉统计</view>
        </view>
        
        <!-- 筛选区域 -->
        <view class="filter-section">
          <view class="filter-row">
            <view class="filter-item">
              <text class="filter-label">统计周期：</text>
              <picker mode="selector" :value="filters.periodIndex" :range="periodOptions" @change="onPeriodChange">
                <view class="date-picker">
                  <text>{{ filters.periodIndex >= 0 ? periodOptions[filters.periodIndex] : '请选择' }}</text>
                  <up-icon name="arrow-down" size="14"></up-icon>
                </view>
              </picker>
            </view>
            
            <view class="filter-item">
               <text class="filter-label">类型：</text>
               <picker :value="filters.typeIndex" :range="appealTypes.map(item => item.name)" @change="onTypeChange">
                  <view class="date-picker">
                   <text>{{ filters.typeIndex >= 0 ? appealTypes[filters.typeIndex].name : '全部' }}</text>
                   <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
              </picker>
            </view>
          </view>
          
          <view class="filter-actions">
            <button class="search-btn" @click="searchData">查询</button>
            <button class="reset-btn" @click="resetFilters">重置</button>
          </view>
        </view>
        
        <!-- 统计摘要 -->
        <view class="summary-section">
          <view class="summary-card">
            <view class="summary-title">申请总数</view>
            <view class="summary-value">{{ summary.totalCount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">已处理数</view>
            <view class="summary-value">{{ summary.processedCount }}</view>
          </view>
          <view class="summary-card">
            <view class="summary-title">属实数</view>
            <view class="summary-value">{{ summary.validCount }}</view>
          </view>
        </view>
        
        <!-- 列表表头 -->
        <view class="list-header">
          <text class="list-cell">类型</text>
          <text class="list-cell">申请数</text>
          <text class="list-cell">已处理</text>
          <text class="list-cell">属实数</text>
        </view>
      </template>
      
      <!-- 列表内容 -->
      <view v-for="(item, index) in dataList" :key="index" class="list-row" @click="openDetail(item)">
        <view class="list-cell transaction-cell">
          <view class="transaction-tag appeal-tag" :class="getTagClass(item.typeValue)">
            {{ item.typeName }}
          </view>
        </view>
        <text class="list-cell">{{ item.totalCount }}次</text>
        <text class="list-cell">{{ item.processedCount }}次</text>
        <text class="list-cell">{{ item.validCount }}次</text>
      </view>
    </z-paging>
    
    <!-- 详情弹窗 -->
    <view class="detail-modal" v-if="showDetailModal">
      <view class="detail-content">
        <view class="detail-header">
          <text class="detail-title">{{ currentDetail ? currentDetail.typeName + ' 详情' : '详情信息' }}</text>
          <text class="close-btn" @click="showDetailModal = false">×</text>
        </view>
        
        <view class="detail-body" v-if="currentDetail">
          <view class="detail-item">
            <text class="detail-label">类型：</text>
            <view class="detail-value">
              <view class="transaction-tag appeal-tag" :class="getTagClass(currentDetail.typeValue)">
                {{ currentDetail.typeName }}
              </view>
            </view>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">统计周期：</text>
            <text class="detail-value">{{ periodOptions[filters.periodIndex] }}</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">申请总数：</text>
            <text class="detail-value">{{ currentDetail.totalCount }}次</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">已处理数：</text>
            <text class="detail-value">{{ currentDetail.processedCount }}次</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">属实数：</text>
            <text class="detail-value">{{ currentDetail.validCount }}次</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">处理率：</text>
            <text class="detail-value">{{ currentDetail.processRate }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">属实率：</text>
            <text class="detail-value">{{ currentDetail.validRate }}%</text>
          </view>
          
          <view class="detail-item">
            <text class="detail-label">平均处理时长：</text>
            <text class="detail-value">{{ currentDetail.avgProcessTime }}小时</text>
          </view>
          
          <view class="detail-item" v-if="currentDetail.timeDistribution && currentDetail.timeDistribution.length > 0">
            <text class="detail-label">时段分布：</text>
            <view class="detail-value">
              <view v-for="(time, idx) in currentDetail.timeDistribution" :key="idx" class="time-item">
                {{ time.name }}: {{ time.count }}次 ({{ time.percentage }}%)
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, computed } from 'vue'

// 筛选表单
const filters = reactive({
  periodIndex: 0,
  typeIndex: -1
})

// 统计周期选项
const periodOptions = [
  '日统计',
  '月统计',
  '年统计'
]

// 投申诉类型
const appealTypes = [
  { name: '全部', value: 'all' },
  { name: '申诉', value: 'appeal' },
  { name: '投诉', value: 'complaint' },
  { name: '咨询', value: 'consultation' }
]

// 列表数据
const dataList = ref([])
const paging = ref(null)

// 统计摘要数据
const summary = reactive({
  totalCount: '0次',
  processedCount: '0次',
  validCount: '0次'
})

// 详情弹窗
const showDetailModal = ref(false)
const currentDetail = ref(null)

// 获取标签样式类
const getTagClass = (type) => {
  switch(type) {
    case 'appeal':
      return 'appeal-type-tag'
    case 'complaint':
      return 'complaint-type-tag'
    case 'consultation':
      return 'consultation-type-tag'
    default:
      return ''
  }
}

// 统计周期选择处理
const onPeriodChange = (e) => {
  filters.periodIndex = parseInt(e.detail.value)
}

// 类型选择处理
const onTypeChange = (e) => {
  filters.typeIndex = parseInt(e.detail.value)
}

// 查询数据
const searchData = () => {
  if (paging.value) {
    paging.value.reload()
  }
}

// 重置筛选条件
const resetFilters = () => {
  filters.periodIndex = 0
  filters.typeIndex = -1
  
  nextTick(() => {
    if (paging.value) {
      paging.value.reload()
    }
  })
}

// 查询列表数据
const queryList = (pageNo, pageSize) => {
  // 模拟请求延迟
  setTimeout(() => {
    // 生成模拟数据
    const data = generateMockData(pageNo, pageSize)
    paging.value.complete(data)
    
    // 更新统计摘要
    updateSummary(data)
  }, 500)
}

// 更新统计摘要
const updateSummary = (data) => {
  // 计算总申请数、已处理数和属实数
  let totalCount = 0
  let processedCount = 0
  let validCount = 0
  
  data.forEach(item => {
    totalCount += item.totalCount
    processedCount += item.processedCount
    validCount += item.validCount
  })
  
  // 更新摘要数据
  summary.totalCount = totalCount + '次'
  summary.processedCount = processedCount + '次'
  summary.validCount = validCount + '次'
}

// 生成模拟数据
const generateMockData = (pageNo, pageSize) => {
  const data = []
  
  // 时段分布
  const timeDistributions = [
    { name: '早上(6:00-10:00)', value: 'morning' },
    { name: '中午(10:00-14:00)', value: 'noon' },
    { name: '下午(14:00-18:00)', value: 'afternoon' },
    { name: '晚上(18:00-22:00)', value: 'evening' },
    { name: '深夜(22:00-6:00)', value: 'night' }
  ]
  
  // 筛选类型
  let filteredTypes = [...appealTypes.slice(1)] // 排除'全部'选项
  if (filters.typeIndex > 0) { // 0是全部，大于0才需要筛选
    filteredTypes = [appealTypes[filters.typeIndex]]
  }
  
  // 计算总申请次数（用于计算占比）
  const totalAppealCount = Math.floor(Math.random() * 500) + 100 // 100-600次
  
  // 生成随机数据
  for (const appealType of filteredTypes) {
    // 根据类型设置不同的分布
    let countPercentage, processedPercentage, validPercentage, avgProcessTime
    
    if (appealType.value === 'appeal') {
      countPercentage = Math.random() * 0.2 + 0.3 // 30%-50%
      processedPercentage = Math.random() * 0.2 + 0.7 // 70%-90%
      validPercentage = Math.random() * 0.3 + 0.4 // 40%-70%
      avgProcessTime = Math.random() * 24 + 24 // 24-48小时
    } else if (appealType.value === 'complaint') {
      countPercentage = Math.random() * 0.2 + 0.2 // 20%-40%
      processedPercentage = Math.random() * 0.2 + 0.8 // 80%-100%
      validPercentage = Math.random() * 0.2 + 0.3 // 30%-50%
      avgProcessTime = Math.random() * 12 + 12 // 12-24小时
    } else {
      countPercentage = Math.random() * 0.2 + 0.1 // 10%-30%
      processedPercentage = Math.random() * 0.1 + 0.9 // 90%-100%
      validPercentage = Math.random() * 0.1 + 0.8 // 80%-90%
      avgProcessTime = Math.random() * 6 + 6 // 6-12小时
    }
    
    const totalCount = Math.floor(totalAppealCount * countPercentage)
    const processedCount = Math.floor(totalCount * processedPercentage)
    const validCount = Math.floor(processedCount * validPercentage)
    
    // 生成时段分布
    const timeDistribution = []
    let remainingCount = totalCount
    
    for (let i = 0; i < timeDistributions.length; i++) {
      const isLast = i === timeDistributions.length - 1
      const timeCount = isLast ? remainingCount : Math.floor(remainingCount * (Math.random() * 0.4 + 0.1)) // 10%-50%
      
      if (timeCount > 0) {
        const timePercentage = ((timeCount / totalCount) * 100).toFixed(2)
        
        timeDistribution.push({
          name: timeDistributions[i].name,
          count: timeCount,
          percentage: timePercentage
        })
        
        remainingCount -= timeCount
      }
      
      if (remainingCount <= 0) break
    }
    
    // 添加数据
    data.push({
      typeName: appealType.name,
      typeValue: appealType.value,
      totalCount,
      processedCount,
      validCount,
      processRate: ((processedCount / totalCount) * 100).toFixed(2),
      validRate: ((validCount / processedCount) * 100).toFixed(2),
      avgProcessTime: avgProcessTime.toFixed(2),
      timeDistribution
    })
  }
  
  // 按申请总数排序
  return data.sort((a, b) => b.totalCount - a.totalCount)
}

// 打开详情弹窗
const openDetail = (item) => {
  currentDetail.value = item
  showDetailModal.value = true
}

// 页面加载时查询数据
onMounted(() => {
  searchData()
})
</script>

<style lang="scss" scoped>
.appeal-complaint-stats-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.list-paging {
  height: 100%;
}

.page-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx 30rpx 30rpx;
  color: white;
  
  .header-title {
    font-size: 36rpx;
    font-weight: bold;
    text-align: center;
  }
}

.filter-section {
  background-color: white;
  padding: 20rpx 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .filter-row {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20rpx;
  }
  
  .filter-item {
    flex: 1;
    min-width: 300rpx;
    margin-bottom: 10rpx;
    display: flex;
    align-items: center;
    
    .filter-label {
      font-size: 28rpx;
      color: #333;
      margin-right: 10rpx;
      white-space: nowrap;
    }
    
    .date-picker {
      flex: 1;
      height: 60rpx;
      border: 1px solid #ddd;
      border-radius: 6rpx;
      padding: 0 20rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 28rpx;
    }
  }
  
  .filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 20rpx;
    
    button {
      min-width: 160rpx;
      height: 70rpx;
      line-height: 70rpx;
      font-size: 28rpx;
      margin: 0;
      padding: 0 30rpx;
    }
    
    .search-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    
    .reset-btn {
      background-color: #f5f5f5;
      color: #666;
    }
  }
}

.summary-section {
  display: flex;
  justify-content: space-between;
  padding: 0 20rpx;
  margin-bottom: 20rpx;
  
  .summary-card {
    flex: 1;
    background-color: white;
    border-radius: 10rpx;
    padding: 20rpx;
    margin: 0 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    text-align: center;
    
    .summary-title {
      font-size: 24rpx;
      color: #666;
      margin-bottom: 10rpx;
    }
    
    .summary-value {
      font-size: 32rpx;
      color: #333;
      font-weight: bold;
    }
  }
}

.list-header {
  display: flex;
  background-color: #f8f8f8;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
  border-bottom: 1px solid #eee;
}

.list-row {
  display: flex;
  background-color: white;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #f5f5f5;
}

.list-cell {
  flex: 1;
  display: flex;
  align-items: center;
}

.transaction-cell {
  display: flex;
  align-items: center;
}

.transaction-tag {
  padding: 6rpx 16rpx;
  border-radius: 6rpx;
  font-size: 24rpx;
  color: white;
}

.appeal-tag {
  background-color: #4CAF50;
}

.appeal-type-tag {
  background-color: #2196F3;
}

.complaint-type-tag {
  background-color: #FF9800;
}

.consultation-type-tag {
  background-color: #9C27B0;
}

.detail-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: center;
}

.detail-content {
  width: 80%;
  max-height: 80%;
  background-color: white;
  border-radius: 10rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.detail-header {
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .detail-title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .close-btn {
    font-size: 40rpx;
    line-height: 1;
  }
}

.detail-body {
  padding: 30rpx;
  overflow-y: auto;
  flex: 1;
  
  .detail-item {
    margin-bottom: 20rpx;
    display: flex;
    
    .detail-label {
      width: 200rpx;
      font-size: 28rpx;
      color: #666;
    }
    
    .detail-value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .time-item {
      margin-bottom: 10rpx;
    }
  }
}
</style>